package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private IBpmnInfoService bpmnInfoService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private IServiceItemService serviceItemService;
    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public InputStream getProcessImageByAuditId(Long id) {
        CarPackageAudit audit = this.get(id);
        String instanceId = audit.getInstanceId();
        List<String> highLightedActivities = null;
        //处于审核中
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            highLightedActivities = runtimeService.getActiveActivityIds(instanceId);
        } else {
            highLightedActivities = new ArrayList<>();
        }
        //根据bpmninfoID查询到BpmnInfo对象,再查到对应的流程实例ID
        Long bpmnInfoId = audit.getBpmnInfoId();
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);
        BpmnModel model = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());

        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        return generator.generateDiagram(model, highLightedActivities, Collections.emptyList(),
                "宋体", "宋体", "宋体");
    }

    @Override
    public void cancelApply(Long id) {
        CarPackageAudit audit = this.get(id);
        carPackageAuditMapper.changeAuditStatus(id,CarPackageAudit.STATUS_CANCEL);
        serviceItemService.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
        runtimeService.deleteProcessInstance(audit.getInstanceId(), "撤销审核");
    }

    @Override
    public void audit(Long id, int auditStatus, String info) {
        //先判断状态
        CarPackageAudit carPackageAudit = this.get(id);
        if(carPackageAudit==null || !CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            throw new BusinessException("只有处于审核状态的记录才能进行审核操作");
        }
        String userName = ShiroUtils.getUser().getUserName();
        if(CarPackageAudit.STATUS_PASS.equals(auditStatus)){
            info = userName+"【同意】,批注意见:"+info;
        }else{
            info = userName+"【拒绝】,批注意见:"+info;
        }
        carPackageAudit.setInfo(carPackageAudit.getInfo()+"<br>"+info);
        Task currentTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
        taskService.setVariable(currentTask.getId(),"auditStatus",auditStatus);
        taskService.addComment(currentTask.getId(),carPackageAudit.getInstanceId(),info);
        taskService.complete(currentTask.getId());
        //获取下一个节点
        Task nextTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
        if(CarPackageAudit.STATUS_PASS.equals(auditStatus)){
            if(nextTask!=null){
                //财务审核
                carPackageAudit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
                carPackageAudit.setAuditTime(new Date());
            }else{
                //审核通过
                serviceItemService.updateAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
                carPackageAudit.setStatus(CarPackageAudit.STATUS_PASS);
            }
        }else{
            //审核拒绝
            serviceItemService.updateAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);
            carPackageAudit.setStatus(CarPackageAudit.STATUS_REJECT);
        }
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }
}
